//https://leetcode.cn/problems/binary-tree-level-order-traversal/
package codeRandomThoughts.Test102二叉树的层序遍历;

import codeRandomThoughts.utils.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

//层序遍历三刷
public class Solution3 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        List<List<Integer>> results = new ArrayList<>();

        Queue<TreeNode> queue = new LinkedList<>();
        int npl = 0;//每层的结点数

        if (root == null) {
            return results;
        }
        queue.offer(root);

        while (!queue.isEmpty()) {
            npl = queue.size();
            while (npl > 0) {
                TreeNode poll = queue.poll();
                if (poll.left != null) {
                    queue.offer(poll.left);
                }
                if (poll.right != null) {
                    queue.offer(poll.right);
                }

                result.add(poll.val);
                npl--;
            }
            results.add(result);
            result = new ArrayList<>();
        }
        return results;
    }
}
